package com.xq.security.provider;

import com.xq.security.CustomUserDetailsService;
import com.xq.security.token.SmsCodeAuthenticationToken;
import com.xq.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 自定义手机验证码登录的provider 要在springSecurity中使其放行
 */
@Component
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SmsService smsService;

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String phone = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();

        //验证验证码是否正确
        if(!smsService.validateCode(phone, code)){
            throw new RuntimeException("验证码错误或已过期");
        }

        //查询用户，若用户不存在则报错
        UserDetails user;
        try{
            //根据手机号查询
            //ATTENTION 这里原本是根据用户名查的 可能之后会出错
            user = userDetailsService.loadUserByPhone(phone);
        }catch (UsernameNotFoundException e){
            //TODO 这里之后可以实现如果用户不存在则自动注册的代码
            throw new UsernameNotFoundException("用户不存在");
        }

        return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
